<template>
	<div class="order-manager">
		<!-- 顶部统计卡片 -->
		<div class="stats-card">
			<div v-if="summaryLoading" class="summary-loading">
				<u-loading-icon text="加载统计数据"></u-loading-icon>
			</div>
			<div v-else class="stat-row">
				<div class="stat-item" v-for="(stat, index) in stats" :key="index">
					<div class="stat-icon" :style="{ backgroundColor: stat.bgColor }">
						<u-icon :name="stat.icon" size="24" :color="stat.color"></u-icon>
					</div>
					<div class="stat-content">
						<div class="stat-value">{{ stat.value }}</div>
						<div class="stat-label">{{ stat.label }}</div>
					</div>
				</div>
			</div>
		</div>

		<!-- 筛选区域 -->
		<div class="filter-section">
			<u-tabs :list="statusTabs" :current="curNow" @change="handleStatusChange"></u-tabs>
			<div class="filter-controls">
				<!-- <u-input
					v-model="searchParams.keyword"
					placeholder="搜索订单号/商品名称"
					clearable
					border="surround"
					shape="circle"
					@clear="handleSearch"
					@blur="handleSearch"
				>
					<template #suffix>
						<u-icon name="search" size="20" @click="handleSearch"></u-icon>
					</template>
				</u-input> -->
				<u-button class="date-range-btn" icon="calendar" shape="circle" @click="showDatePicker = true">
					{{ dateRangeTitle }}
				</u-button>
			</div>
		</div>

		<u-calendar
			:show="showDatePicker"
			mode="range"
			@confirm="handleDateConfirm"
			@close="showDatePicker = false"
			:minDate="new Date(2025, 0, 1).getTime()"
			:maxDate="new Date(2035, 11, 31).getTime()"
			:monthNum="48"
		></u-calendar>

		<!-- 订单列表 -->
		<scroll-view class="order-list-container" scroll-y :style="scrollViewStyle" @scrolltolower="loadMore">
			<view class="order-list">
				<div v-if="loading" class="loading-container">
					<u-loading-icon text="加载中"></u-loading-icon>
				</div>

				<div v-else-if="orderList.length === 0" class="empty-state">
					<u-empty mode="order" text="暂无订单数据"></u-empty>
				</div>

				<div v-else>
					<div v-for="order in orderList" :key="order.id" class="order-card">
						<!-- 订单头部 -->
						<div class="order-header">
							<div class="order-no">订单号: {{ order.no }}</div>
							<u-tag :text="getStatusText(order.status)" :type="getStatusType(order.status)"></u-tag>
						</div>

						<!-- 商品列表 -->
						<div v-for="item in order.items" :key="item.id" class="order-item">
							<u-image :src="item.picUrl" width="80" height="80" radius="4" mode="aspectFill"></u-image>
							<div class="item-info">
								<div class="item-name">{{ item.spuName }}</div>
								<div v-if="item.properties && item.properties.length > 0" class="item-specs">
									<span v-for="(prop, idx) in item.properties" :key="idx">
										{{ prop.valueName }}<u-line v-if="idx < item.properties.length - 1" direction="col" length="12" margin="0 8px"></u-line>
									</span>
								</div>
								<div class="item-price">¥{{ formatAmount(item.payPrice || 0) }}</div>
							</div>
							<div class="item-quantity">x{{ item.count }}</div>
						</div>

						<!-- 订单信息 -->
						<div class="order-summary">
							<div class="summary-item">
								<span>共{{ order.productCount }}件商品</span>
								<span
									>合计: <span class="total-price">¥{{ formatAmount(order.payPrice || 0) }}</span></span
								>
							</div>
							<div class="summary-item">
								<span>下单时间</span>
								<span>{{ formatTime(order.createTime) }}</span>
							</div>
							<div v-if="order.receiverName" class="summary-item">
								<span>收货信息</span>
								<span>{{ order.receiverName }} {{ order.receiverMobile }} {{ order.receiverDetailAddress }}</span>
							</div>
						</div>

						<!-- 操作按钮 -->
						<div class="order-actions">
							<u-button v-if="order.status === 10" size="small" shape="circle" @click="handleDelivery(order)">发货</u-button>

							<u-button size="small" shape="circle" plain @click="showOrderDetail(order)">详情</u-button>

							<u-button v-if="order.status === 20 && order.deliveryType === 2" size="small" shape="circle" type="primary" @click="handlePickUp(order)"
								>核销</u-button
							>
						</div>
					</div>
				</div>

				<!-- 分页加载提示 -->
				<view class="loadmore-container">
					<u-loadmore :status="pagination.status" :load-text="loadText" :nomore-text="'没有更多订单了'" :margin-top="30" :margin-bottom="30" />
				</view>
			</view>
		</scroll-view>

		<!-- 订单详情弹窗 -->
		<!-- 		<u-popup v-model="detailVisible" mode="center" round="16" closeable>
			<OrderDetail v-if="currentOrder" :order="currentOrder" @close="detailVisible = false" @refresh="fetchOrders" />
		</u-popup> -->

		<!-- 发货弹窗 -->
		<u-popup :show="deliveryVisible" mode="bottom" round="16">
			<DeliveryForm v-if="currentOrder" :order-id="currentOrder.id" @submit="handleDeliverySubmit" @cancel="deliveryVisible = false" />
		</u-popup>
		<!-- 调试信息 -->
		<!-- 
		<div>deliveryVisible: {{ deliveryVisible }}</div>
		<div>currentOrder: {{ currentOrder ? currentOrder.id : 'null' }}</div> -->
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue';
import dayjs from 'dayjs';
import OrderDetail from '../OrderDetail/OrderDetail.vue';
import DeliveryForm from '../DeliveryForm/DeliveryForm.vue';
import type { OrderVO, TradeOrderSummaryRespVO, DeliveryVO } from '@/api/mall/trade/order';
import { getOrderPage, getOrderSummary, deliveryOrder } from '@/api/mall/trade/order';
import { useOrderStore } from '@/store/modules/order';
let useStore = useOrderStore();
// 在原有代码基础上，添加以下样式计算属性
const scrollViewStyle = computed(() => {
	// 计算可滚动区域的高度（视口高度减去顶部区域高度）
	// const statsCardHeight = 180; // 顶部统计卡片高度
	// const filterSectionHeight = 80; // 筛选区域高度
	// const statusBarHeight = 20; // 状态栏高度（小程序环境）

	const statsCardHeight = 180; // 顶部统计卡片高度
	const filterSectionHeight = 80; // 筛选区域高度
	const statusBarHeight = 20; // 状态栏高度（小程序环境）
	return `height: calc(100vh - ${statsCardHeight + filterSectionHeight + statusBarHeight}px);`;
});
// 订单状态映射
const ORDER_STATUS = {
	0: { text: '待付款', type: 'warning' },
	10: { text: '待发货', type: 'primary' },
	20: { text: '已发货', type: 'info' },
	30: { text: '已完成', type: 'success' },
	40: { text: '已取消', type: 'error' },
	50: { text: '部分发货', type: 'warning' },
};

// 状态定义
const statusTabs = [
	{ name: '全部', label: 'all', badge: { isDot: true } },
	{ name: '待付款', label: '0' },
	{ name: '待发货', label: '10' },
	{ name: '已发货', label: '20' },
	{ name: '已完成', label: '30' },
	{ name: '已取消', label: '40' },
];

const searchParams = reactive({
	status: 'all',
	keyword: '',
	startTime: '',
	endTime: '',
});

const dateRange = ref<string[]>([]);
const showDatePicker = ref(false);
const summary = ref<TradeOrderSummaryRespVO>({
	orderCount: 0,
	orderPayPrice: 0,
	afterSaleCount: 0,
	afterSalePrice: 0,
});
const summaryLoading = ref(true);
const loading = ref(true);
const detailVisible = ref(false);
const deliveryVisible = ref(false);
const currentOrder = ref<OrderVO | null>(null);
const pagination = reactive({
	page: 1,
	pageSize: 10,
	total: 0,
	status: 'loadmore',
});

const loadText = {
	loadmore: '点击加载更多',
	loading: '正在加载...',
	nomore: '没有更多了',
};

// 计算卡片数据
const stats = computed(() => [
	{
		label: '订单金额',
		value: `¥${formatAmount(summary.value.orderPayPrice)}`,
		icon: 'rmb-circle-fill',
		color: '#fff',
		bgColor: '#ff6b6b',
	},
	{
		label: '订单数量',
		value: summary.value.orderCount,
		icon: 'order-fill',
		color: '#fff',
		bgColor: '#4dabf7',
	},
	{
		label: '退款金额',
		value: `¥${formatAmount(summary.value.afterSalePrice)}`,
		icon: 'refund-fill',
		color: '#fff',
		bgColor: '#ff922b',
	},
	{
		label: '退款单数',
		value: summary.value.afterSaleCount,
		icon: 'file-text-fill',
		color: '#fff',
		bgColor: '#40c057',
	},
]);

// 修改日期范围标签计算
const dateRangeTitle = computed(() => {
	if (dateRange.value.length < 2) {
		return '选择日期范围';
	}
	const start = dayjs(dateRange.value[0]);
	const end = dayjs(dateRange.value[1]);

	// 如果同月，则显示为"MM月DD日 - DD日"
	if (start.isSame(end, 'month')) {
		return `${start.format('MM月DD日')} - ${end.format('DD日')}`;
	}
	return `${start.format('MM月DD日')} - ${end.format('MM月DD日')}`;
});

// 格式化金额
const formatAmount = (value: number) => {
	return (value / 100).toFixed(2);
};

// 格式化时间
const formatTime = (date: Date | null) => {
	return date ? dayjs(date).format('YYYY-MM-DD HH:mm') : '--';
};

// 获取状态文本
const getStatusText = (status: number | null) => {
	if (status === null || status === undefined) return '未知';
	return ORDER_STATUS[status as keyof typeof ORDER_STATUS]?.text || '未知';
};

// 获取状态类型
const getStatusType = (status: number | null) => {
	if (status === null || status === undefined) return 'info';
	return ORDER_STATUS[status as keyof typeof ORDER_STATUS]?.type || 'info';
};
const curNow = ref(0);
// 状态变更处理
const handleStatusChange = (index: any) => {
	searchParams.status = index.label;

	fetchOrders();
};

// 日期确认处理
const handleDateConfirm = (e: any) => {
	let startDate, endDate;
	if (typeof e === 'object' && 'startDate' in e) {
		startDate = e.startDate;
		endDate = e.endDate;
	} else if (Array.isArray(e) && e.length >= 2) {
		startDate = e[0];
		endDate = e[e.length - 1];
	} else {
		console.error('未知的日期格式:', e);
		return;
	}

	dateRange.value = [startDate, endDate];
	searchParams.startTime = dayjs(startDate).format('YYYY-MM-DD');
	searchParams.endTime = dayjs(endDate).format('YYYY-MM-DD');
	showDatePicker.value = false;
	fetchOrders();
};

// 搜索处理
const handleSearch = () => {
	pagination.page = 1;
	fetchOrders();
};

// 加载更多
// 加载更多方法（保留原有loadMore方法）
const loadMore = () => {
	console.log('pagination.status===', pagination.status);
	if (pagination.status === 'nomore') {
		console.log('没有更多数据了');
		return;
	}

	if (pagination.status === 'loading') {
		console.log('正在加载中');
		return;
	}

	// 设置加载状态
	//pagination.status = 'loading';

	// 获取下一页数据
	setTimeout(async () => {
		try {
			pagination.page += 1;
			await loadOrderData(true);
			console.log('pagination.page += 1', pagination.page);
			// 更新加载状态
			if (orderList.value.length >= pagination.total) {
				pagination.status = 'nomore';
			} else {
				pagination.status = 'loadmore';
			}
		} catch (error) {
			console.error('加载更多失败:', error);
			pagination.status = 'loadmore';
			uni.showToast({
				title: '加载失败，请重试',
				icon: 'error',
			});
		}
	}, 800);
};

// 获取统计数据
const loadSummaryData = async () => {
	summaryLoading.value = true;
	if (!searchParams.startTime || searchParams.startTime === '') {
		searchParams.startTime = dayjs().format('YYYY-MM-DD');
	}
	if (!searchParams.endTime || searchParams.endTime === '') {
		searchParams.endTime = dayjs().format('YYYY-MM-DD');
	}
	try {
		// 将日期字符串转换为ISO格式（LocalDateTime）
		const startTimeISO = dayjs(searchParams.startTime).startOf('day').format('YYYY-MM-DD HH:mm:ss');
		const endTimeISO = dayjs(searchParams.endTime).endOf('day').format('YYYY-MM-DD HH:mm:ss');

		// 构建参数对象
		const params: any = {
			status: searchParams.status === 'all' ? undefined : Number(searchParams.status),
			keyword: searchParams.keyword,
			//createTime: [startTimeISO, endTimeISO],
		};

		// 添加数组参数，使用索引形式
		params['createTime[0]'] = startTimeISO + '';
		params['createTime[1]'] = endTimeISO + '';

		const res = await getOrderSummary(params);
		summary.value = res.data;
	} catch (error) {
		console.error('获取统计数据失败', error);
		uni.showToast({
			title: '获取统计数据失败',
			icon: 'error',
		});
	} finally {
		summaryLoading.value = false;
	}
};

// 存储订单列表数据
const orderList = ref<OrderVO[]>([]);

// 加载订单数据
const loadOrderData = async (loadMore = false) => {
	if (!loadMore) {
		loading.value = true;
		pagination.page = 1;
		pagination.status = 'loading';
	} else {
		// 避免重复加载
		if (pagination.status === 'loading') return;
		pagination.status = 'loading';
	}
	if (!searchParams.startTime || searchParams.startTime === '') {
		searchParams.startTime = dayjs().format('YYYY-MM-DD');
	}
	if (!searchParams.endTime || searchParams.endTime === '') {
		searchParams.endTime = dayjs().format('YYYY-MM-DD');
	}
	// 将日期字符串转换为ISO格式（LocalDateTime）
	const startTimeISO = dayjs(searchParams.startTime).startOf('day').format('YYYY-MM-DD HH:mm:ss');
	const endTimeISO = dayjs(searchParams.endTime).endOf('day').format('YYYY-MM-DD HH:mm:ss');

	try {
		const params = {
			pageNo: pagination.page,
			pageSize: pagination.pageSize,
			status: searchParams.status === 'all' ? undefined : Number(searchParams.status),
			keyword: searchParams.keyword,
		};
		// 添加数组参数，使用索引形式
		params['createTime[0]'] = startTimeISO + '';
		params['createTime[1]'] = endTimeISO + '';
		const { data } = await getOrderPage(params);
		console.log('params====>', params);

		if (loadMore) {
			orderList.value = [...orderList.value, ...data.list];
		} else {
			orderList.value = data.list;
		}

		pagination.total = data.total;

		// 更新加载状态
		if (orderList.value.length >= pagination.total) {
			pagination.status = 'nomore';
		} else {
			pagination.status = 'loadmore';
		}

		// 如果没有数据
		if (pagination.total === 0) {
			pagination.status = 'nomore';
		}
	} catch (error) {
		console.error('获取订单列表失败', error);
		uni.showToast({
			title: '获取订单列表失败',
			icon: 'error',
		});
	} finally {
		loading.value = false;
	}
};

// 获取订单数据
const fetchOrders = async () => {
	await Promise.all([loadSummaryData(), loadOrderData()]);
};

// 查看订单详情
const showOrderDetail = (order: OrderVO) => {
	//currentOrder.value = order;
	//detailVisible.value = true;
	const orderData = encodeURIComponent(JSON.stringify(order));
	uni.navigateTo({
		url: `/pages/order/OrderDetail/OrderDetail?orderData=${orderData}`, // 通过 URL 传递数据
	});
};

// 处理发货
const handleDelivery = (order: OrderVO) => {
	console.log('点击发货，订单信息:', order);
	currentOrder.value = order;
	deliveryVisible.value = true;
	console.log('deliveryVisible 设置为 true');
};

// 处理核销
const handlePickUp = (order: OrderVO) => {
	uni.showModal({
		title: '订单核销',
		content: `确定要核销订单 ${order.no} 吗？`,
		success: async (res) => {
			if (res.confirm) {
				uni.showToast({
					title: '核销成功',
					icon: 'success',
				});
				// 模拟API调用
				await new Promise((resolve) => setTimeout(resolve, 500));
				fetchOrders();
			}
		},
	});
};

// 处理发货提交
const handleDeliverySubmit = async (data: DeliveryVO) => {
	uni.showToast({
		title: '发货成功',
		icon: 'success',
	});
	console.log('订单列表发货接收的数据==》', data);
	deliveryVisible.value = false;
	// 模拟API调用
	await deliveryOrder(data);
	fetchOrders();
};

// 初始化加载
onMounted(() => {
	fetchOrders();
});
</script>

<style lang="scss" scoped>
.order-list-container {
	box-sizing: border-box;
	overflow: hidden;
	background: linear-gradient(135deg, #fff9c4 0%, #ffffff 100%);

	.order-list {
		padding-bottom: 20px;
	}

	.loadmore-container {
		display: flex;
		justify-content: center;
		padding: 10px 0;
		background: white;
	}
}
.order-manager {
	padding: 16px;
	background-color: #f5f7fa;
	min-height: 100vh;
}

.stats-card {
	margin-bottom: 16px;
	background: #fff;
	border-radius: 16px;
	padding: 16px;
	box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
	background: linear-gradient(to bottom, #f5f0ff, #ffffff);

	.stat-row {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 12px;

		@media (min-width: 768px) {
			grid-template-columns: repeat(4, 1fr);
		}
	}

	.stat-item {
		display: flex;
		align-items: center;
		padding: 16px;
		background: #f9fafc;
		border-radius: 12px;
		transition: all 0.3s;

		&:hover {
			transform: translateY(-3px);
			box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
		}
	}

	.stat-icon {
		width: 48px;
		height: 48px;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 12px;
	}

	.stat-content {
		flex: 1;

		.stat-value {
			font-size: 18px;
			font-weight: bold;
			margin-bottom: 4px;
			color: #303133;
		}

		.stat-label {
			font-size: 13px;
			color: #909399;
		}
	}

	.summary-loading {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 120px;
	}
}

.filter-section {
	background: #fff;
	border-radius: 12px;
	padding: 12px 16px;
	margin-bottom: 16px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
	background: linear-gradient(to bottom, #e6f7ff, #f0f9ff, #ffffff);

	.filter-controls {
		display: flex;
		flex-direction: column;
		gap: 12px;
		margin-top: 12px;

		@media (min-width: 576px) {
			flex-direction: row;
		}

		.u-input {
			flex: 1;
		}

		.u-button {
			width: 100%;

			@media (min-width: 576px) {
				width: 160px;
			}
		}

		.date-range-btn {
			background: linear-gradient(45deg, #6a11cb, #2575fc);
			color: white !important;
			border: none;
		}
	}
}

.order-list {
	.loading-container,
	.empty-state {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 50vh;
		background: #fff;
		border-radius: 16px;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.03);
	}
}

.order-card {
	background: #fff;
	border-radius: 12px;
	margin-bottom: 16px;
	padding: 16px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
	transition: all 0.3s;

	&:hover {
		transform: translateY(-3px);
		box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
	}

	.order-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-bottom: 12px;
		border-bottom: 1px solid #f1f1f1;
		margin-bottom: 12px;

		.order-no {
			font-size: 14px;
			color: #606266;
			font-weight: 500;
		}
	}

	.order-item {
		display: flex;
		padding: 12px 0;
		border-bottom: 1px dashed #f1f1f1;

		&:last-child {
			border-bottom: none;
		}

		.u-image {
			margin-right: 12px;
			flex-shrink: 0;
			border-radius: 8px;
			overflow: hidden;
		}

		.item-info {
			flex: 1;
			overflow: hidden;

			.item-name {
				font-size: 15px;
				font-weight: 500;
				margin-bottom: 6px;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
			}

			.item-specs {
				display: flex;
				align-items: center;
				font-size: 12px;
				color: #909399;
				margin-bottom: 6px;
				flex-wrap: wrap;
			}

			.item-price {
				font-size: 14px;
				font-weight: bold;
				color: #f56c6c;
			}
		}

		.item-quantity {
			font-size: 14px;
			color: #909399;
			align-self: flex-start;
		}
	}

	.order-summary {
		margin-top: 12px;
		padding-top: 12px;
		border-top: 1px solid #f1f1f1;

		.summary-item {
			display: flex;
			justify-content: space-between;
			font-size: 13px;
			color: #606266;
			margin-bottom: 6px;

			&:last-child {
				margin-bottom: 0;
			}

			.total-price {
				font-weight: bold;
				color: #f56c6c;
			}
		}
	}

	.order-actions {
		display: flex;
		justify-content: flex-end;
		gap: 8px;
		margin-top: 16px;

		.u-button {
			min-width: 80px;
			border-radius: 20px;
		}
	}
}
</style>
